package com.hmkj.quote.queue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmkj.boot.utils.SpringContextUtils;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.constant.PointNid;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.operate.PointRuleService;
import lombok.extern.slf4j.Slf4j;

/**
 * 积分奖励发放队列
 *
 * @author eproo
 * @date 2017年03月16日 21:38
 */
@Slf4j
public class PointQueueThread implements Runnable {


    private RedisService redisService = SpringContextUtils.getBean(RedisService.class);
    private PointRuleService pointRuleService = SpringContextUtils.getBean(PointRuleService.class);

    @Override
    public void run() {
        while (true) {
            try {
                if (startQueue()) {
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private boolean startQueue() throws Exception {
        boolean isFinish = false;
        try {
            JSONObject obj = redisService.pop(CacheID.QUEUE_POINT, JSONObject.class);
            if (null == obj) {
                return true;
            }
            log.info("积分发放：" + JSON.toJSONString(obj));
            // 发放积分
            pointRuleService.doSendPoint(obj.getInteger("userId"), PointNid.getByNid(obj.getString("nid")));
        } catch (Exception e) {
            log.error("积分发放队列失败：" + e.getMessage());
            e.printStackTrace();
        }
        return isFinish;
    }
}
